var hmlineup = {
  teamID: 0,
  dataDirectories: [],
  currentLineup: [],
  positionCodes: new Array("idKeeper","idRightBack","idInsideBack1","idInsideBack2","idLeftBack","idRightWinger","idInsideMid1","idInsideMid2","idLeftWinger","idForward1","idForward2","idSubstKeeper","idSubstBack","idSubstInsideMid","idSubstWinger","idSubstForward","idKicker1","idCaptain"),
  behaviourCodes: new Array("","behRightBack","behInsideBack1","behInsideBack2","behLeftBack","behRightWinger","behInsideMid1","behInsideMid2","behLeftWinger","behForward1","behForward2","","","","","","",""),
  nodeNames: new Array("PlayerID","RoleID","PositionCode","Behaviour"),
  stringbundle: null,

  init: function()
  {
    this.stringbundle = document.getElementById("hmlineup-strings");

    var dataDirectoryPath = null;
    
    // Try to use the new interface added in FF 1.5
    if ("@mozilla.org/windows-registry-key;1" in Components.classes)
    {
      var regkey = Components.classes["@mozilla.org/windows-registry-key;1"].getService(Components.interfaces.nsIWindowsRegKey);
      regkey.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, "Software\\HattrickManager\\Download", Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
      dataDirectoryPath = regkey.readStringValue("DataDirectory");
    }
    else
    {
      // Fallback on old interfaces if the new one don't exists
      var winhooks = null;
      if ("@mozilla.org/browser/shell-service;1" in Components.classes)
      {
        winhooks = Components.classes["@mozilla.org/browser/shell-service;1"].getService(Components.interfaces.nsIWindowsShellService);
      }
      else if ("@mozilla.org/winhooks;1" in Components.classes)
      {
        winhooks = Components.classes["@mozilla.org/winhooks;1"].getService(Components.interfaces.nsIWindowsRegistry);
      }
      if (winhooks)
      {
        dataDirectoryPath = winhooks.getRegistryEntry(2, "Software\\HattrickManager\\Download", "DataDirectory");
      }
    }

    if (dataDirectoryPath)
    {
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
      file.initWithPath(dataDirectoryPath);
      if (file.exists() && file.isDirectory())
      {
        var entries = file.directoryEntries;
        this.dataDirectories = [];
        while(entries.hasMoreElements())
        {
          var entry = entries.getNext();
          entry.QueryInterface(Components.interfaces.nsIFile);
          this.dataDirectories.push(entry);
        }
      }
    }
  },

  printXML: function(node)
  {
    if (!node.childNodes || node.childNodes.length == 0)
      return "<"+ node.tagName +">"+ node.nodeValue +"</"+ node.tagName +">\n";

    var str = "";
    str += "<"+ node.tagName +">\n";
    for (var i in node.childNodes)
    {
      str += this.printXML(node.childNodes[i]);
    }
    str += "</"+ node.tagName +">\n";
    return str;
  },

  updatePlayerLineup: function (aEvent)
  {
    doc = aEvent.originalTarget;
    while (doc.parentNode)
    {
      doc = doc.parentNode;
    }

    if (this.currentLineup && this.currentLineup.exists())
    {
      contents = this.readFile(this.currentLineup);
      var parser = new DOMParser();
      var dom = parser.parseFromString(contents, "text/xml");
      var results = this.evaluateXPath(dom, "/HMData/Lineup/Player");

      var players = [];
      for (var i = 0; i < results.length; i++)
      {
        players[i] = new Object();
        for (var j = 0; j < results[i].childNodes.length; j++)
        {
          node = results[i].childNodes[j];
          if (this.nodeNames.indexOf(node.nodeName) > -1)
          {
            players[i][node.nodeName] = node.childNodes[0].textContent;
          }
        }
      }

      lineupPlayers = [];
      for (var i = 0; i < players.length; i++)
      {
        lineupPlayers[players[i]["RoleID"]-1] = players[i];
      }

      var inputs = doc.getElementsByTagName("select");
      for (var j = 0; j < inputs.length; j++)
      {
        input = inputs.item(j);
        positionIndex = this.positionCodes.indexOf(input.getAttribute("name"))
        if (positionIndex > -1)
        {
          input.value = lineupPlayers[positionIndex]["PlayerID"];
        }
        else
        {
          behaviourIndex = this.behaviourCodes.indexOf(input.getAttribute("name"))
          if (behaviourIndex > -1)
          {
            input.value = lineupPlayers[behaviourIndex]["Behaviour"];
          }
        }
      }  
    }
  },

  onPageLoad: function (aEvent)
  {
    var doc = aEvent.originalTarget;
    var url = doc.location;
    var host = "";
    try {
      host = url.host;
    }
    catch(e) {
      return;
    }

    if (doc && url && host.match(/\.hattrick\.org$/))
    {
      switch (url.pathname.toLowerCase())
      {
        case "/common/header.asp":
          if (doc.body && (match = doc.body.innerHTML.match(/teamID=([\d]+)"/)))
            this.teamID = match[1];

          break;
        case "/common/matchorders.asp":
          if (this.dataDirectories && this.dataDirectories.length)
          {
            var dataDirectory = null;
            for (var i = 0; i < this.dataDirectories.length; i++)
            {
              if (this.dataDirectories[i].leafName == this.teamID)
              {
                dataDirectory = this.dataDirectories[i];
                break;
              }
            }

            if (!dataDirectory)
              return;

            this.currentLineup = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            this.currentLineup.initWithFile(dataDirectory);
            this.currentLineup.append("hmSettings");
            this.currentLineup.append("currentLineup.xml");
            if (!this.currentLineup.exists())
              return;

            var elems = doc.getElementsByTagName("form");
            var elem = null;
            for (var i = 0; i < elems.length; i++)
            {
              if (elems[i].getAttribute("name") == "matchOrders")
              {
                elem = elems[i];
                break;
              }
            }

            if (elem)
            {
              while (elem.nodeName != "TABLE" && elem.previousSibling)
              {
                elem = elem.previousSibling;
              }

              var htmlRow = elem.insertRow(1);

              var htmlCell = htmlRow.insertCell(0);
              htmlCell.setAttribute("COLSPAN", 4);
              htmlCell.setAttribute("ALIGN", "right");

              var htmlTable = htmlCell.appendChild(doc.createElement("TABLE"));
              htmlTable.setAttribute("CELLPADDING", "4");
              htmlTable.setAttribute("CELLSPACING", "0");
              htmlTable.setAttribute("BORDER", "0");
              htmlTable.setAttribute("STYLE", "border: 1px solid #000000; background-color: #F7F6F4; margin: 4px; margin-right: 0px;");

              var htmlRow = htmlTable.insertRow(0);
              var htmlCell = htmlRow.insertCell(0);

              var htmlImage = htmlCell.appendChild(doc.createElement("IMG"));
              htmlImage.setAttribute("SRC", "chrome://hmlineup/content/images/hme.gif");
              htmlImage.setAttribute("WIDTH", 24);
              htmlImage.setAttribute("HEIGHT", 15);

              var htmlCell = htmlRow.insertCell(1);
              var htmlButton = htmlCell.appendChild(doc.createElement("INPUT"));
              htmlButton.setAttribute("ID", "hattrickmanagerButton");
              htmlButton.setAttribute("TYPE", "button");
              htmlButton.setAttribute("VALUE", this.stringbundle.getString("hm.importLineup"));
              htmlButton.addEventListener("click", function(aEvent) { hmlineup.updatePlayerLineup(aEvent); }, false);
            }
          }
          break;
      }
    }
  },

  evaluateXPath: function(aNode, aExpr) {
    var xpe = new XPathEvaluator();
    var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?
      aNode.documentElement : aNode.ownerDocument.documentElement);
    var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
    var found = [];
    while (res = result.iterateNext())
      found.push(res);
    return found;
  },

  readFile: function(fp)
  {
    var text = "";
    var file = Components.classes["@mozilla.org/file/local;1"]
                         .createInstance(Components.interfaces.nsILocalFile);
    file.initWithFile(fp);
    if(file.exists())
    {
      try {
        var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
                                .createInstance(Components.interfaces.nsIFileInputStream);
        fis.init(file, 1, 0, false);

        var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
                                .createInstance(Components.interfaces.nsIScriptableInputStream);
        sstream.init(fis);
        var header = sstream.read(3);

        if (header == "\xEF\xBB\xBF")
        {
          fis.close();
          fis.init(file, 1, 0, false);

          if (!("@mozilla.org/intl/converter-input-stream;1" in Components.classes))
            alert('You must update Firefox');

          var charset = "UTF-8";
          const replacementChar = Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
          var is = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
                             .createInstance(Components.interfaces.nsIConverterInputStream);
          is.init(fis, charset, 1024, replacementChar);
          var str = {};
          while (is.readString(4096, str) != 0)
            text += str.value;
        }
        else
        {
          text = header;
          text += sstream.read(-1);
        }
      }
      catch (e)
      {
        return "";
      }
      finally
      {
        if (sstream)
          sstream.close();
        if (is)
          is.close();
        if (fis)
          fis.close();
      }
    }
    return text;
  }
}

addEventListener("load", onInit, false);
addEventListener("unload", onUninit, false);

function onInit()
{
  hmlineup.init();
  document.getElementById("appcontent").addEventListener("DOMContentLoaded", function(aEvent) { hmlineup.onPageLoad(aEvent); }, true);
}

function onUninit()
{
  document.getElementById("appcontent").removeEventListener("DOMContentLoaded", function(aEvent) { hmlineup.onPageLoad(aEvent); }, true);
}

// Make Array.indexOf work in Firefox versions older than 1.1
if  (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(item)
  {
    for (var i = 0; i < this.length; i++)
        if (this[i] == item)
            return i;
    return -1;
  };
}